package com.yf.dxapp.module.app.controller.app;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import com.yf.dxapp.module.app.component.app.AppCourseComponent;
import com.yf.dxapp.module.app.component.app.QiniuFileComponent;
import com.yf.dxapp.module.app.controller.admin.category.vo.CategoryPageReqVO;
import com.yf.dxapp.module.app.controller.app.vo.ClassificationVo;
import com.yf.dxapp.module.app.controller.app.vo.CommonRequest;
import com.yf.dxapp.module.app.controller.app.vo.CourseListRequest;
import com.yf.dxapp.module.app.controller.app.vo.CourseReportRequest;
import com.yf.dxapp.module.app.dal.dataobject.appbanner.AppBannerDO;
import com.yf.dxapp.module.app.dal.dataobject.appuser.AppUserDO;
import com.yf.dxapp.module.app.dal.dataobject.category.CategoryDO;
import com.yf.dxapp.module.app.enums.app.AppBehaviorTypeEnum;
import com.yf.dxapp.module.app.enums.app.AppCategoryTypeEnum;
import com.yf.dxapp.module.app.enums.app.BannerTypeEnum;
import com.yf.dxapp.module.app.service.appbanner.AppBannerService;
import com.yf.dxapp.module.app.service.behavior.BehaviorService;
import com.yf.dxapp.module.app.service.category.CategoryService;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * @author yxmds
 */
@RestController
@RequestMapping("/course")
public class ApiAppCourseController extends ApiAppBaseController {

    @Resource
    private AppCourseComponent courseComponent;

    @Resource
    private CategoryService categoryService;

    @Resource
    private BehaviorService behaviorService;

    @Resource
    private AppBannerService appBannerService;

    @Resource
    private QiniuFileComponent qiniuFileComponent;

    /**
     * POST /api/app/mini/course/classification : 课程分类
     */
    @RequestMapping(value = "/classification",
            method = RequestMethod.POST)
    @PermitAll
    public CommonResult appCourseClassification() {
        CategoryPageReqVO query = new CategoryPageReqVO();
        query.setParentType(AppCategoryTypeEnum.COURSE_ROOT.getType());
        PageResult<CategoryDO> result = categoryService.getCategoryPage(query);
        return success(result.getList().stream().map(ClassificationVo::build).collect(Collectors.toList()));
    }


    @RequestMapping(value = "/ad-material",
            method = RequestMethod.POST)
    @PermitAll
    public CommonResult appCourseAdMaterial() {
        List<AppBannerDO> list = appBannerService.findByType(BannerTypeEnum.COURSE.getIndex());
        return success(list.stream().map(banner -> {
            banner.setImg(qiniuFileComponent.complementImgUrl(banner.getImg()));
            return banner;
        }).collect(Collectors.toList()));
    }

    @RequestMapping(value = "/ad-my-material",
            method = RequestMethod.POST)
    @PermitAll
    public CommonResult appMyCourseAdMaterial() {
        List<AppBannerDO> list = appBannerService.findByType(BannerTypeEnum.MY_COURSE.getIndex());
        return success(list.stream().map(banner -> {
            banner.setImg(qiniuFileComponent.complementImgUrl(banner.getImg()));
            return banner;
        }).collect(Collectors.toList()));
    }

    /**
     * POST /api/app/mini/course/detail : 课程详情
     */
    @RequestMapping(value = "/detail",
            method = RequestMethod.POST)
    public CommonResult appCourseDetail(@RequestBody CommonRequest request) {
        Long courseId = request.getId();
        return success(courseComponent.getDouxinCourseVo(courseId, SecurityFrameworkUtils.getLoginUserId()));

    }


    /**
     * POST /api/app/mini/course/list : 课程列表
     */
    @RequestMapping(value = "/list",
            method = RequestMethod.POST)
    @PermitAll
    public CommonResult appCourseList(@Valid @RequestBody(required = true) CourseListRequest courseListRequest) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        return success(courseComponent.getCourseList(loginUserId, courseListRequest));
    }

    /**
     * POST /api/app/mini/course/report-schedule : 课程进度上报
     */
    @RequestMapping(value = "/report-schedule",
            method = RequestMethod.POST)
    public CommonResult appCourseReportSchedule(@Valid @RequestBody(required = true) CourseReportRequest courseReportRequest) {
        // TODO 记录上报日志
        Long refId;
        if (courseReportRequest == null) {
            return error(-1, "上报日志信息为空");
        }
        if (courseReportRequest.getId() == null) {
            return error(-1, "上报日志主体为空");
        }
        refId = ObjectUtils.defaultIfNull(courseReportRequest.getItemId(), courseReportRequest.getId());
        if (courseReportRequest.getTimes() == null) {
            return error(-1, "课程上报的时长信息为空");
        }
//        String behavior = "用户观看课程视频，已累计观看" + convertToChineseTime(courseReportRequest.getTimes());
        String behavior = "用户观看课程视频，已累计观看" + courseReportRequest.getTimes();
        behaviorService.record(SecurityFrameworkUtils.getLoginUserId(), refId, AppBehaviorTypeEnum.WATCH_COURSE.getKey(), behavior, 10);
        return success(true);
    }

    private static String convertToChineseTime(int seconds) {
        if (seconds < 0) {
            throw new IllegalArgumentException("秒数不能为负数");
        }

        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        int remainingSeconds = seconds % 60;

        if (hours > 0) {
            return MessageFormat.format("{0}小时{1}分钟{2}秒", hours, minutes, remainingSeconds);
        } else if (minutes > 0) {
            return MessageFormat.format("{0}分钟{1}秒", minutes, remainingSeconds);
        } else {
            return MessageFormat.format("{0}秒", remainingSeconds);
        }
    }

    /**
     * app我的课程
     *
     * @return
     */
    @RequestMapping("/my-list")
    public CommonResult appCourseMyCollectList(@Valid @RequestBody CourseListRequest courseListRequest) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId == null) {
            // 返回 401
            return error(HttpStatus.UNAUTHORIZED.value(), "账号未登录");
        }
        AppUserDO userEntity = getLoginUser(loginUserId);
        if (userEntity == null) {
            // 返回 401
            return error(HttpStatus.UNAUTHORIZED.value(), "登录用户无效，请重新注册");
        }
        return success(courseComponent.getMyCourseList(loginUserId, courseListRequest));
    }
}
